package com.ynet.middleground.approve.listener.contract;

import java.util.List;
import java.util.Optional;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.approve.cmd.SpringContextUtils;
import com.ynet.middleground.approve.listener.BaseListener;
import com.ynet.middleground.approve.model.ContractCenterModel;

/**
 * @author liulx
 * @description 判断模板是否可以变更为其他状态监听器，在合约模板的激活、停用流程中使用
 * @date 2020-07-09 14:47
 */
@DependsOn("springContextUtils")
@Service
public class CheckTemplateConditionListener extends BaseListener implements ExecutionListener {

    /**
     * 引入发送合约模板模块
     */
    protected ContractCenterModel contractCenterModel = SpringContextUtils.getBean(ContractCenterModel.class);

    @Override
    public void notify(DelegateExecution delegateExecution) {
        String channel = getChannel(delegateExecution);
        String operationUserId = getOperationUserId(delegateExecution);
        // 从流程中获取需要更新的模板 id 集合
        Object list =
            getObjectVariableInstance(delegateExecution, UpdateContractTemplateStatusListener.TEMPLATE_IDS_KEY);
        Optional.ofNullable(list).orElseThrow(() -> new BusinessException(
            "变量: " + UpdateContractTemplateStatusListener.TEMPLATE_IDS_KEY + " 不存在", "ECAP0506"));
        // 从流程中获取激活、停用标志
        Object templateStatus =
            getObjectVariableInstance(delegateExecution, UpdateContractTemplateStatusListener.TEMPLATE_STATUS_KEY);
        Optional.ofNullable(templateStatus).orElseThrow(() -> new BusinessException(
            "变量: " + UpdateContractTemplateStatusListener.TEMPLATE_STATUS_KEY + " 不存在", "ECAP0506"));

        if (list instanceof List<?>) {
            List<Integer> templateIds = (List<Integer>)list;
            contractCenterModel.checkTemplateCondition(templateIds, String.valueOf(templateStatus), channel,
                Integer.valueOf(operationUserId));
        }
    }

}
